/** @type {import('./_venera_.js')} */
class Hmtt extends ComicSource {
    // 注意: 标记为[可选]的字段如果不使用应删除

    // 源名称
    name = "韩漫天堂"

    // 源的唯一标识
    key = "hmtt"

    version = "1.0.0"

    minAppVersion = "1.4.0"

    // 更新链接
    url = "https://gitee.com/cmj_xxgg/comic_yuan/blob/master/hmtt.js"

    /**
     * [可选] 初始化函数
     */
    init() {
        this.baseUrl = "https://www.hmtt.com"

    }

      /// 解析漫画列表 id网址 title标题 cover封面 description作者
    parseComic(e) {
        let url = e.querySelector("a").attributes["href"];
        let id = url.split("/").pop().replace(/\.html$/, "");
        let title = e.querySelector("a").text.trim();
        let cover = e.querySelector("a > img").attributes["src"];
        return {
            id: id,
            title: title,
            cover: cover,
        };
    }

    /// 搜索相关
    search = {
        /**
         * 加载搜索结果
         * @param keyword {string}
         * @param options {string[]} - options from optionList
         * @param page {number}
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        load: async (keyword, options, page) => {
            //https://www.hmttmh.com/search.html?keyword=高武
            let res = await Network.get(`${this.baseUrl}/search.html?keyword=${keyword}.html`);
            if (res.status !== 200) {
                throw "Invalid status code: " + res.status;
            }
            let document = new HtmlDocument(res.body);
            let comics = document
                .querySelectorAll("ul")
                .map((e) => this.parseComic(e));
            return {
                comics: comics,
                maxPage: 1,
            };
        },

        /**
         * 使用下一页令牌加载搜索结果。
         * The field will be ignored if `load` function is implemented.
         * @param keyword {string}
         * @param options {(string)[]} - options from optionList
         * @param next {string | null}
         * @returns {Promise<{comics: Comic[], maxPage: number}>}
         */
        loadNext: async (keyword, options, next) => {

        },

        // 为搜索提供选项
        optionList: [
            {
                // [可选] 默认是`select`
                // 类型: select（单选）, multi-select（多选）, dropdown（下拉菜单）
                // select类型只能选择一个值
                // multi-select类型可以选择多个值或不选。`load`函数将接收一个JSON字符串，是选中值的数组
                // dropdown类型最多选择一个值。如果没有选中值，`load`函数将接收null
                type: "select",
                // For a single option, use `-` to separate the value and text, left for value, right for text
                options: [
                    "0-time",
                    "1-popular"
                ],
                // 选项标签
                label: "sort",
                // 默认选中选项。如果未设置，使用第一个选项作为默认值
                default: null,
            }
        ],

        // 启用标签建议
        enableTagsSuggestions: false,
    }

    comic = {
        // 加载漫画信息
        loadInfo: async (id) => {
        let res = await Network.get(`${this.baseUrl}/comic/${id}`);
        if (res.status !== 200) {
            throw "Invalid status code: " + res.status;
        }
        let document = new HtmlDocument(res.body);

        // 解析漫画信息
        let title = document.querySelector("div.cy_title").text.trim();
        let cover = document.querySelector("div.cy_info_cover > img")
            .attributes["src"];
        let author = document
            .querySelector("div.cy_xinxi")
            .text.trim();
        let updateTime = document
            .querySelector("div.cy_zhangjie_top p:last-child")
            ?.text.trim()
            .replace("更新时间：", "");
        let description = document
            .querySelector("div.cy_desc")
            .text.trim();
        let chapters = new Map();
        let i = 0;
        for (let c of document.querySelectorAll(
            "mh-chapter-list-ol-0 > li > a > p"
        )) {
            chapters.set(i.toString(), c.text.trim());
            i++;
        }
        if (i === 0) {
            // 将倒序的最新章节反转
            const spans = Array.from(
            document.querySelectorAll("mh-chapter-list-ol-0 > li > a > p")
            ).reverse();
            for (let c of spans) {
            chapters.set(i.toString(), c.text.trim());
            i++;
            }
        }
        let recommend = [];
        for (let c of document.querySelectorAll("div.cy_kanguo_list")) {
            if (c.querySelectorAll("ul.li").length > 0) {
            let title = c.querySelector("b").text.trim();
            let cover = c.querySelector("amp-img").attributes["src"];
            let url = c.querySelector("a").attributes["href"];
            let id = url.split("/").pop();
            recommend.push({
                id: id,
                title: title,
                cover: cover,
            });
            }
        }
        // updateTime 将 Y年 M月 D日 转化为 Y-M-D
        let updateDate = updateTime
            .replace(/年/g, "-")
            .replace(/月/g, "-")
            .replace(/日/g, "");

        return new ComicDetails({
            title: title,
            cover: cover,
            description: description,
            tags: {
            作者: [author],
            标签: tags,
            },
            chapters: chapters,
            recommend: recommend,
            updateTime: updateDate,
        });
        },

        loadEp: async (comicId, epId) => {
            const images = [];
            let currentPageUrl = `${this.baseUrl}/comic/chapter/${comicId}/0_${epId}.html`;
            let maxAttempts = 100;

            while (maxAttempts > 0) {
                const res = await Network.get(currentPageUrl);
                if (res.status !== 200) break;

                // 解析当前页图片
                const doc = new HtmlDocument(res.body);
                doc
                .querySelectorAll("ul.comic-contain > div > img")
                .forEach((img) => {
                    const src = img?.attributes?.["src"];
                    if (typeof src === "string") images.push(src);
                });

                // 查找下一页链接
                const nextLink = doc.querySelector("a#mainControlNext");
                if (nextLink?.text?.match(/点击进入下一话|下一頁/)) {
                currentPageUrl = nextLink.attributes["href"];
                } else {
                break;
                }
                maxAttempts--;
            }
            return images; // 添加此行返回图片数组
        },
    };
}